<template>
  <div class="redu_root">
    <div class="step_one step_form" v-show="stepActive === 1">
      <el-form
        :model="createForm"
        :rules="createFormRules"
        ref="createForm"
        label-width="120px"
        class="form-com-css"
      >
        <div class="border-c">
          <el-form-item
            style="margin-top: 14px"
            label="活动名称"
            prop="activityName"
            :rules="[
              { required: true, message: '活动名称不能为空', trigger: 'blur' },
              { validator: validatecouponRemark, trigger: 'blur' },
            ]"
          >
            <el-input
              placeholder="请输入活动名称"
              style="width: 500px"
              v-model="createForm.activityName"
              :disabled="!isEdit"
            />
          </el-form-item>
          <el-form-item label="活动ID">
            <el-input
              placeholder="无须输入，系统自动生成"
              style="width: 500px"
              v-model="createForm.id"
              :disabled="true"
            />
          </el-form-item>
        </div>

        <el-form-item
          prop="selectionCouponList"
          label-width="30px"
          class="border-c"
        >
          <div class="t">参与活动的优惠券</div>
          <div style="margin-bottom: 10px">
            <el-button type="primary" @click="getCouponList" :disabled="!isEdit"
              >添加优惠券</el-button
            >
          </div>
          <div>
            <el-table
              border
              :data="selectionCouponList"
              height="400px"
              class="tableStyle"
            >
              <el-table-column type="index" label="序号" align="left">
              </el-table-column>
              <el-table-column
                prop="couponRemark"
                label="优惠券名称"
                align="left"
              >
              </el-table-column>
              <el-table-column prop="id" label="优惠券ID" align="left" />
              <el-table-column
                prop="stationName"
                label="关联油站"
                align="left"
              />
              <el-table-column
                prop="couponThresholdAmt"
                label="使用条件"
                align="left"
                show-overflow-tooltip
              >
                <!-- <template slot-scope="scope">
                  <el-input @input="changeMember(scope.$index)" v-model="scope.row.minUseCouponAmt"
                    v-if="updateSwitch && scope.$index === updateIndex"
                    :placeholder="scope.row.minUseCouponAmt !== null ? scope.row.minUseCouponAmt : '请输入'"></el-input>
                  <span v-else>{{ scope.row.minUseCouponAmt }}</span>
                </template> -->
              </el-table-column>
              <el-table-column
                prop="couponDetails"
                label="优惠说明"
                align="left"
                show-overflow-tooltip
              />
              <el-table-column
                prop="endDate"
                label="发放结束时间"
                align="left"
              />
              <el-table-column prop="couponName" label="操作" align="left">
                <template slot-scope="scope">
                  <el-button
                    @click="
                      delRowEvent(
                        'selectionCouponList',
                        scope.$index,
                        scope.row
                      )
                    "
                    type="text"
                    size="small"
                    :disabled="!isEdit"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <div class="using_limit">
          <div class="title">​使用限制</div>
          <el-table
            :data="limitList"
            border
            size="mini"
            style="width: 100%"
            v-loading="limitLoading"
          >
            <el-table-column
              prop="couponAmt"
              label="优惠券额度"
              align="center"
            >
            <template slot-scope="{ row }">
              {{ row.couponType  ===  "4"? '洗车券'+ row.couponAmt + "元" : ''}}
              {{ row.couponType  ===  "2"? row.couponAmt + "%" : ''}}
              {{ row.couponType  ===  "1"? row.couponAmt + "元": ''}}
              {{ row.couponType  ===  "5"? "每升立减" + row.couponAmt + "元": ''}}
            </template>
            </el-table-column>
            <el-table-column
              prop="couponNum"
              label="优惠券数量(张)"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="dayCount"
              label="每日可使用(张)"
              align="center"
            >
              <template slot-scope="{ row }">
                <el-input @blur="checkVal(row)" v-model="row.dayCount"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="moonCount"
              label="每月可使用(张)"
              align="center"
            >
              <template slot-scope="{ row }">
                <el-input @blur="checkVal(row)" v-model="row.moonCount"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-form-item
          class="border-c"
          prop="activityStartTime"
          label-width="30px"
          :rules="{
            required: true,
            message: '请选择开始时间',
            trigger: 'change',
          }"
        >
          <div class="t">活动开始时间</div>
          <div @click="getStartTime">
            <el-radio
              :disabled="!isEdit"
              v-model="stepTwoData.isimm"
              label="isimm"
              >立即执行</el-radio
            >
          </div>
          <div class="date-css">
            <el-date-picker
              :disabled="!isEdit"
              v-model="createForm.activityStartTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期"
            >
            </el-date-picker>
          </div>
        </el-form-item>

        <el-form-item
          class="border-c"
          prop="activityEndTime"
          label-width="30px"
          :rules="{
            required: true,
            message: '请选择结束时间',
            trigger: 'change',
          }"
        >
          <div class="t">活动结束时间</div>
          <div class="date-css">
            <el-date-picker
              :disabled="!isEdit"
              v-model="createForm.activityEndTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <!-- <el-form-item
          class="border-c"
          prop="stepTwoData.antiCheating"
        >
          <div class="t">单日能参与次数  </div>
          <div
            class="disflx three-b"
            style="margin-bottom: 10px"
          >

            <el-input
              :disabled="true"
              v-model="stepTwoData.countOfDay"
              style="width: 500px;"
            ></el-input>

          </div>
        </el-form-item> -->
        <el-form-item
          label-width="30px"
          class="border-c"
          label=""
          prop="issueType"
          :rules="{
            required: true,
            message: '请选择发放类型',
            trigger: 'change',
          }"
        >
          <div class="t">发放类型</div>
          <div class="disflx one-alert" style="margin-bottom: 10px">
            <el-radio
              :disabled="!isEdit"
              v-model="createForm.issueType"
              label="0"
              >手动领取</el-radio
            >
          </div>
          <div class="disflx one-alert" style="margin-bottom: 10px">
            <el-radio
              @input="inputIssueType"
              :disabled="!isEdit"
              v-model="createForm.issueType"
              label="5"
              >注册会员后自动发放</el-radio
            >
          </div>
          <div class="disflx one-alert" style="margin-bottom: 10px">
            <el-radio
              :disabled="!isEdit"
              v-model="createForm.issueType"
              label="1"
              >支付成功后发放</el-radio
            >
          </div>
          <div class="disflx one-alert" style="margin-bottom: 10px">
            <el-radio
              :disabled="!isEdit"
              v-model="createForm.issueType"
              label="6"
              >推荐成功后发放</el-radio
            >
          </div>
          <!-- <div class="disflx one-alert" style="margin-bottom: 10px">
            <el-radio :disabled="true" v-model="createForm.issueType" label="2"
              >plus会员专用</el-radio
            >
          </div>
          <div class="disflx one-alert" style="margin-bottom: 10px">
            <el-radio :disabled="true" v-model="createForm.issueType" label="3"
              >数据预录入模板（给用户导入优惠券时使用）</el-radio
            >
          </div> -->
        </el-form-item>

        <el-form-item
          prop="distributionType"
          class="border-c"
          v-if="createForm.issueType === '1'"
        >
          <!-- <div class="t">加油订单金额满多少可享受
          </div>
          <div class="disflx one-alert" style="margin-bottom: 10px">
            <el-input v-model.number="createForm.activityThreshold" placeholder="请输入内容" />
          </div> -->
          <div class="t">发放门槛</div>
          <div>
            <div>
              <el-radio
                :disabled="!isEdit"
                v-model="createForm.distributionType"
                label="0"
                >定值</el-radio
              >
              <el-radio
                :disabled="!isEdit"
                v-model="createForm.distributionType"
                label="1"
                >阶梯</el-radio
              >
            </div>
            <div></div>
          </div>
          <div v-if="createForm.distributionType == '0'">
            消费达到
            <input
              type="text"
              :disabled="!isEdit"
              class="form-control d-inline-block"
              v-model.number="createForm.activityThreshold"
              style="width: 120px; margin: 0 5px"
            />元时，{{ createForm.issueType == 1 ? "系统自动发放" : ""
            }}{{ createForm.issueType == 3 ? "触发领取页" : "" }}
          </div>
          <!-- <hr v-if="createForm.distributionType == 'ladder'" /> -->
          <div v-if="createForm.distributionType == '1'">
            <el-button
              :disabled="!isEdit"
              type="primary"
              size="mini"
              @click="addThresholdLadder"
              >添加阈值</el-button
            >
            <div
              v-for="(item, index) in createForm.thresholdLadder"
              :key="index"
              style="margin-bottom: 10px"
            >
              消费达<input
                :disabled="!isEdit"
                type="text"
                class="form-control d-inline-block"
                v-model.number="createForm.thresholdLadder[index].value"
                style="width: 120px; margin: 0 5px"
              />元时，系统自发发放优惠券：
              <span>
                <!-- <el-checkbox v-model="createForm.thresholdLadder[index].couponList" :label="ele.id.toString()"
                  v-for="ele in selectionCouponList" :key="ele.id">{{ ele.couponRemark + "--" + ele.id }}</el-checkbox> -->
                <el-select
                  :disabled="!isEdit"
                  v-model="createForm.thresholdLadder[index].couponList"
                  multiple
                  collapse-tags
                  style="margin-left: 20px"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in selectionCouponList"
                    :key="item.id"
                    :label="item.couponRemark"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </span>
              <span>
                <el-button
                  :disabled="!isEdit"
                  @click="deleteThresholdLadder(index)"
                  style="margin-left: 20px"
                  size="mini"
                  >删除</el-button
                >
              </span>
            </div>
          </div>
        </el-form-item>

        <el-form-item
          class="border-c"
          label-width="30px"
          prop="memberCondition "
          :rules="{
            required: true,
            validator: validateStepTwoData,
            trigger: 'change',
          }"
        >
          <div class="t">参与活动车主</div>
          <div>
            <el-radio
              :disabled="!isEdit"
              v-model="stepThreeData.memberCondition"
              label="all"
              @input="inputRadioAll"
              >全选</el-radio
            >
            <!-- <el-radio
              :disabled="true"
              v-model="stepThreeData.memberCondition"
              label="plus"
              >plus会员</el-radio
            > -->
            <el-radio
              :disabled="
                !isEdit ||
                this.createForm.issueType === '5' ||
                createForm.issueType === '6'
              "
              v-model="stepThreeData.memberCondition"
              label="part"
              @input="inputRadio"
              >指定</el-radio
            >
          </div>
          <div>
            <el-checkbox
              v-model="stepThreeData.memberLevelList"
              :disabled="!isEdit || stepThreeData.memberCondition !== 'part'"
              label="1"
              class="checkbox-a"
              >普卡</el-checkbox
            >
            <el-checkbox
              v-model="stepThreeData.memberLevelList"
              :disabled="!isEdit || stepThreeData.memberCondition !== 'part'"
              label="2"
              class="checkbox-a"
              >银卡</el-checkbox
            >
            <el-checkbox
              v-model="stepThreeData.memberLevelList"
              :disabled="!isEdit || stepThreeData.memberCondition !== 'part'"
              label="3"
              class="checkbox-a"
              >金卡</el-checkbox
            >
            <el-checkbox
              v-model="stepThreeData.memberLevelList"
              :disabled="!isEdit || stepThreeData.memberCondition !== 'part'"
              label="4"
              class="checkbox-a"
              >钻卡</el-checkbox
            >
            <el-checkbox
              v-model="stepThreeData.memberLevelList"
              :disabled="!isEdit || stepThreeData.memberCondition !== 'part'"
              label="5"
              class="checkbox-a"
              >黑卡</el-checkbox
            >
            <!-- <el-checkbox
              v-model="stepThreeData.memberLevelList"
              :disabled="!isEdit || stepThreeData.memberCondition !== 'part'"
              label="6"
              class="checkbox-a"
              >超级会员</el-checkbox
            > -->
            <el-checkbox
              v-model="stepThreeData.memberLevelList"
              :disabled="!isEdit || stepThreeData.memberCondition !== 'part'"
              label="6"
              class="checkbox-b"
              >超级会员-月卡</el-checkbox
            >
            <el-checkbox
              v-model="stepThreeData.memberLevelList"
              :disabled="!isEdit || stepThreeData.memberCondition !== 'part'"
              label="7"
              class="checkbox-b"
              >超级会员-季卡</el-checkbox
            >
            <el-checkbox
              v-model="stepThreeData.memberLevelList"
              :disabled="!isEdit || stepThreeData.memberCondition !== 'part'"
              label="8"
              class="checkbox-b"
              >超级会员-年卡</el-checkbox
            >
            <!-- <el-checkbox
              v-model="stepThreeData.memberLevelList"
              :disabled="!isEdit || stepThreeData.memberCondition !== 'part'"
              label="6"
              class="checkbox-super"
              >超级会员-月卡</el-checkbox
            >
            <el-checkbox
              v-model="stepThreeData.memberLevelList"
              :disabled="!isEdit || stepThreeData.memberCondition !== 'part'"
              label="6"
              class="checkbox-super"
              >超级会员-季卡</el-checkbox
            >
            <el-checkbox
              v-model="stepThreeData.memberLevelList"
              :disabled="!isEdit || stepThreeData.memberCondition !== 'part'"
              label="6"
              class="checkbox-super"
              >超级会员-年卡</el-checkbox
            > -->
          </div>
          <div>
            <el-checkbox
              v-model="stepThreeData.payMentList"
              :disabled="
                !isEdit ||
                stepThreeData.memberCondition !== 'part' ||
                createForm.issueType !== '1'
              "
              label="1"
              class="checkbox-a"
              >微信</el-checkbox
            >
            <el-checkbox
              v-model="stepThreeData.payMentList"
              :disabled="
                !isEdit ||
                stepThreeData.memberCondition !== 'part' ||
                createForm.issueType !== '1'
              "
              label="2"
              class="checkbox-a"
              >支付宝</el-checkbox
            >
            <!-- <el-checkbox
              v-model="stepThreeData.payMentList"
              :disabled="true"
              label="dzk"
              >会员卡</el-checkbox
            > -->
            <!-- :disabled="stepThreeData.memberCondition !== 'part'" -->
            <el-checkbox
              v-model="stepThreeData.payMentList"
              :disabled="true"
              class="checkbox-a"
              label="3"
            >
              <!-- :disabled="stepThreeData.memberCondition !== 'part'" -->
              现金
            </el-checkbox>
            <el-checkbox
              v-model="stepThreeData.payMentList"
              :disabled="true"
              class="checkbox-a"
              label="4"
            >
              <!-- :disabled="stepThreeData.memberCondition !== 'part'" -->
              银行卡
            </el-checkbox>
            <el-checkbox
              v-model="stepThreeData.payMentList"
              :disabled="
                !isEdit ||
                stepThreeData.memberCondition !== 'part' ||
                createForm.issueType !== '1'
              "
              class="checkbox-a"
              label="5"
            >
              <!-- :disabled="stepThreeData.memberCondition !== 'part'" -->
              电子卡
            </el-checkbox>
            <el-checkbox
              v-model="stepThreeData.payMentList"
              :disabled="
                !isEdit ||
                stepThreeData.memberCondition !== 'part' ||
                createForm.issueType !== '1'
              "
              class="checkbox-a"
              label="6"
            >
              <!-- :disabled="stepThreeData.memberCondition !== 'part'" -->
              实体卡
            </el-checkbox>
          </div>
          <div>
            <el-checkbox
              v-model="stepThreeData.userMentList"
              label="newUser"
              :disabled="true"
              >老用户</el-checkbox
            >
            <!-- :disabled="!isEdit || stepThreeData.memberCondition !== 'part'" -->

            <el-checkbox
              v-model="stepThreeData.userMentList"
              label="oldUser"
              :disabled="true"
              >新用户</el-checkbox
            >
            <el-checkbox
              v-model="stepThreeData.userMentList"
              :disabled="!isEdit || stepThreeData.memberCondition !== 'part'"
              label="1"
              >标签用户</el-checkbox
            >
          </div>
        </el-form-item>
        <div
          class="border-c"
          style="margin-bottom: 20px"
          v-if="createForm.issueType !== '6'"
        >
          <el-form-item
            style="margin-bottom: 0 !important; border-bottom: none !important"
            prop="sendFlag"
            :rules="{
              required: true,
              message: '请选择是否推送',
              trigger: 'change',
            }"
          >
            <div class="t">活动过通知</div>
            <div>是否发送活动通知</div>
            <el-row>
              <el-col :span="21">
                <el-radio-group v-model="createForm.sendFlag">
                  <el-radio :disabled="!isEdit" :label="1">是</el-radio>
                  <el-radio :disabled="!isEdit" :label="0">否</el-radio>
                </el-radio-group>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item
            prop="wxContent"
            v-if="createForm.sendFlag === 1"
            style="border-top: none !important"
            :rules="{
              required: true,
              message: '推送内容不能为空',
              trigger: 'blur',
            }"
          >
            <el-input
              :disabled="!isEdit"
              v-model="createForm.wxContent"
              size="small"
              maxlength="20"
              show-word-limit
              placeholder="推送内容仅限20个字"
              style="width: 400px; display: block; margin-bottom: 10px"
            ></el-input>
          </el-form-item>
        </div>
        <div class="nolable">
          <router-link to="/market/coupon/Coupon_CreateIssue">
            <el-button style="margin-right: 20px">取消</el-button>
          </router-link>

          <el-button
            v-if="isState != '2'"
            type="primary"
            @click="submitForm"
            :disabled="!isEdit"
          >
            保存并提交
          </el-button>
          <el-button
            v-if="isState === '2'"
            type="primary"
            @click="updateAndSubmitForm"
            :disabled="!isEdit"
          >
            修改并提交
          </el-button>
        </div>
      </el-form>
    </div>
    <el-dialog
      :title="'添加优惠券'"
      :visible.sync="couponOpen"
      width="850px"
      append-to-body
    >
      <el-table
        :data="couponList"
        style="width: 100%"
        height="400px"
        ref="couponTable"
        v-loading="loading"
        @selection-change="handleSelectionCouponChange"
      >
        <el-table-column type="selection"> </el-table-column>
        <!-- <el-table-column prop="couponRemark" label="优惠券标识" align="left">
        </el-table-column> -->
        <!-- <el-table-column prop="couponName" label="优惠券名称" align="left"></el-table-column> -->
        <el-table-column prop="couponRemark" label="优惠券名称" align="left">
        </el-table-column>
        <el-table-column prop="id" label="优惠券ID" align="left" />
        <el-table-column prop="stationName" label="关联油站" align="left" />
        <el-table-column
          prop="couponThresholdAmt"
          label="使用条件"
          align="left"
        >
          <!-- <template slot-scope="scope">
                  <el-input @input="changeMember(scope.$index)" v-model="scope.row.minUseCouponAmt"
                    v-if="updateSwitch && scope.$index === updateIndex"
                    :placeholder="scope.row.minUseCouponAmt !== null ? scope.row.minUseCouponAmt : '请输入'"></el-input>
                  <span v-else>{{ scope.row.minUseCouponAmt }}</span>
                </template> -->
        </el-table-column>
        <el-table-column prop="couponDetails" label="优惠说明" align="left" />
        <el-table-column prop="endDate" label="发放结束时间" align="left" />
      </el-table>
      <!-- <div style="text-align: right;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage2"
          :page-sizes="[100, 200, 300, 400]"
          :page-size="100"
          layout="sizes, prev, pager, next"
          :total="1000"
        >
        </el-pagination>
      </div> -->
      <!-- <div slot="footer" class="dialog-footer">
        <el-button
          @click="
            () => {
              couponOpen = false;
            }
          "
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="
            () => {
              couponOpen = false;
            }
          "
          >确定</el-button
        >
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import translateAddress from "@/utils/translateAddress.js";
import {
  addReductionActivity,
  getReductionActivity,
} from "@/api/market/reductionActivity";
import {
  getOilList,
  getStationList,
  addOil,
  upOil,
  delOil,
  getOilListByLogin,
} from "@/api/dept";
import {
  listInfo,
  changeCouponStatus,
  addIssue,
  getCouponActivity,
  upIssueStatus,
  queryCouponInfo,
  addCouponActivity,
  updateCouponActivity,
  getCouponLimit
} from "@/api/coupon";
import { creationList } from "@/api/coupon/creation";
export default {
  name: "Market_Reduction",
  data() {
    var validates = (rule, value, callback) => {
      if (this.createForm.distributionType === "0") {
        if (!this.createForm.activityThreshold) {
          callback(new Error("消费门槛不能为空"));
          return;
        }
        if (Number(this.createForm.activityThreshold) > 1000000) {
          callback(new Error("最大数不能超过7位"));
          return;
        }
        let decimal = this.isDecimal(this.createForm.activityThreshold);
        if (decimal.y > 2 && decimal.x != 0) {
          callback(new Error("小数位不能大于两位"));
          return;
        }
      } else if (this.createForm.distributionType === "1") {
        for (let i = 0; i < this.createForm.thresholdLadder.length; i++) {
          let item = this.createForm.thresholdLadder[i];
          if (!item.value) {
            callback(new Error("消费门槛不能为空"));
            return;
          }
          if (Number(item.value) > 1000000) {
            callback(new Error("最大数不能超过7位"));
            return;
          }
          let decimal = this.isDecimal(item.value);
          if (decimal.y > 2 && decimal.x != 0) {
            callback(new Error("小数位不能大于两位"));
            return;
          }
          if (item.couponList.length === 0) {
            callback(new Error("发放的优惠券不能为空"));
            return;
          }
        }
      }
      callback();
    };
    return {
      limitLoading: false,
      limitList: [],
      // 切换table编辑
      queryForm: {
        status: 1,
      },
      updateSwitch: false,
      currentPage2: 1, // 初始页数
      // 编辑的index
      updateIndex: null,
      activityUse: { CSP: "消费", RCH: "充值" },
      activityType: { RFA: "加油金额", LOR: "加油升数", AAL: "订单金额及升数" },
      activityMode: { FAD: "定额立减", PAR: "百分比立减", RDD: "随机立减" },
      oilList: [],
      stationList: [],
      selectStationList: [],
      selectOilList: [],
      rules: [{ full: "", cut: "", cutMin: "", cutMax: "" }],
      stepActive: 1,
      oilOpen: false,
      stationOpen: false,
      couponOpen: false,
      loading: false,
      couponLoading: false,
      stepOneData: {
        issueRemark: "",
        issueName: "",
        couponThresholdAmt: "",
        oilPartOrAll: 1,
        isimm: "",
        startDate: "",
        endDate: "",
      },
      issueType: "", // 初始化为空值，你可以根据需要设置初始值
      createForm: {
        id: "",
        stationName: "",
        activityName: "",
        activityStatus: "",
        issueType: "0",
        userType: "",
        activityStartTime: null,
        activityEndTime: null,
        totalParticipationTimes: 1,
        issueIds: [],
        activityThreshold: null,
        distributionType: "0",
        thresholdLadder: [
          {
            value: "",
            couponList: [],
          },
        ],
        sendFlag: 1,
      },
      createFormRules: {
        distributionType: [{ validator: validates, trigger: "change" }],
      },
      stepOneRule: {
        activityName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        // activityUse: [
        //   { required: true, message: '请选择活动用途', trigger: 'blur' }
        // ],
        // activityType: [
        //   { required: true, message: '请选择活动类型', trigger: 'blur' }
        // ],
        // activityMode: [
        //   { required: true, message: '请选择活动方式', trigger: 'blur' }
        // ]
      },
      stepTwoData: {
        issueType: "",
        giveCount: "1",
        giveLimit: "999",
        getThresholdAmt: 0,
        antiCheating: "1",
        countOfDay: "1",
        thresholdType: "",
        thresholdLadder: [
          {
            value: "0",
            couponList: [],
          },
        ],
        antiMonthCheating: "1",
        countOfMonth: "1",
        // oilPartOrAll:true,
        // memberCondition:'all',
        // memberLevelList:'',
        // payMentList:'',
        // userMentList:'',
        // isimm: '',
        // startDate: '',
        // endDate: '',
        // maxCount:''
      },
      stepTwoRules: {
        startDate: [
          { required: true, message: "选择开始时间", trigger: "change" },
        ],
        endDate: [
          { required: true, message: "请选择结束时间", trigger: "change" },
        ],
        maxCount: [
          { required: true, message: "请填写最大参与次数", trigger: "change" },
        ],
      },
      stepThreeData: {
        memberCondition: "all",
        memberLevelList: [],
        payMentList: [],
        userMentList: [],
        activityFlag: "0",
      },
      currentOilList: [],
      couponList: [],
      selectionCouponList: [],
      submited: false,
      isEdit: false,
      isState: "0", // 根据实际情况设置 isState 的初始值
      buttonTextMap: {
        0: "保存并提交",
        1: "不可提交",
        2: "修改并提交",
        3: "复制模板提交",
      },
    };
  },
  computed: {
    buttonText() {
      return this.buttonTextMap[this.isState];
    },
  },
  created() {
    this.initData();
  },
  watch: {
    "createForm.sendFlag": {
      handler(newValue) {
        if (newValue === 0) {
          this.createForm.wxContent = ""; //清空输入框
        }
      },
      deep: true,
    },
    couponOpen(val) {
      if(!val && this.selectionCouponList.length > 0) {
       this.getLimitList()
      }
    },
  },
  methods: {
    // 输入框校验方法
    checkVal(row) {
      const val1 = row.dayCount;
      const val2 = row.moonCount;
      const pattern = /^\d{0,6}$/;
      if (val1 && !pattern.test(val1)) {
        this.errMsg("请输入 6 位正整数");
        return false;
      } else if (val2 && !pattern.test(val2)) {
        this.errMsg("请输入 6 位正整数");
        return  false;
      } else if (val1 && val2 && parseInt(val1) > parseInt(val2)) {
        this.errMsg("每日可使用张数需小于等于每月可使用张数");
        return false;
      }
      if(!val1) {
        row.dayCount = null
      }
      if(!val2) {
        row.moonCount = null
      }
      return true;
    },
    errMsg(text) {
      this.$message({
        showClose: true,
        message: text,
        type: "warning",
      });
    },
    // 获取使用限制的表格数据
    async getLimitList() {
      this.limitLoading = true;
      const issueIds = this.selectionCouponList.map(
            (coupon) => coupon.id
          );
        const res = await getCouponLimit(issueIds)
        this.limitList = res.data
        this.limitLoading = false
    },
    // 校验
    validateStepTwoData(rule, value, callback) {
      if (
        this.stepThreeData.memberCondition == "part" &&
        this.createForm.issueType == "0"
      ) {
        if (this.stepThreeData.memberLevelList.length === 0)
          return callback(new Error("请选择参与活动的车主"));
      } else if (
        this.stepThreeData.memberCondition == "part" &&
        this.createForm.issueType == "1"
      ) {
        if (
          this.stepThreeData.memberLevelList.length === 0 ||
          this.stepThreeData.payMentList.length === 0
        )
          return callback(new Error("请选择参与活动的车主"));
      }
      callback();
    },
    inputIssueType() {
      this.stepThreeData.memberCondition = "all";
      this.stepThreeData.memberLevelList = [];
      this.stepThreeData.payMentList = [];
      this.stepThreeData.userMentList = [];
    },
    // 点击全选
    inputRadioAll() {
      this.stepThreeData.memberCondition = "all";
      this.stepThreeData.memberLevelList = [];
      this.stepThreeData.payMentList = [];
      this.stepThreeData.userMentList = [];
      // console.log("点击全选", this.stepThreeData.memberCondition);
    },
    // 点击指定
    inputRadio() {
      this.stepThreeData.memberCondition = "part";
      // console.log("点击指定", this.stepThreeData.memberCondition);
    },
    isDecimal(num) {
      let data = {};
      data.x = String(num).indexOf(".") + 1;
      data.y = String(num).length - data.x;
      return data;
    },
    validateActiveRemark(rule, value, callback) {
      if (value.length === 0) {
        callback(new Error("参与活动的优惠券不能为空"));
      } else {
        callback();
      }
    },
    validatecouponRemark(rule, value, callback) {
      if (value.length > 20) {
        callback(new Error("优惠券名称不能超过20个字符"));
      } else {
        callback();
      }
    },
    handleButtonClick() {
      // console.log(this.isState);
      if (this.isState === 0) {
        this.submitForm();
      }
      if (this.isState === 2) {
        this.updateAndSubmitForm();
      }
      if (this.isState === 3) {
        this.submitForm();
      }
    },
    handleSizeChange(newSize) {
      // 处理分页大小改变事件
      // newSize 参数是新的分页大小
      //   console.log("New page size:", newSize);
      //   // 可以在这里更新数据或发送请求来获取新的数据
    },
    handleCurrentChange(newPage) {
      // 处理当前页数改变事件
      // newPage 参数是新的当前页数
      //   console.log("New current page:", newPage);
      //   // 可以在这里更新数据或发送请求来获取新的数据
    },
    changeMember(index) {
      this.selectionCouponList[index].minUseCouponAmt =
        this.selectionCouponList[index].minUseCouponAmt.replace(/[^\d]/g, "");
      // console.log(this.selectionCouponList[index].minUseCouponAmt);
    },
    switchEdit(index) {
      this.updateIndex = index;
      this.updateSwitch = !this.updateSwitch;
    },
    submitTable(index, value) {
      this.updateSwitch = false;
    },
    initData() {
      var id = this.$route.query.id;
      this.isEdit = this.$route.query.isEdit;
      this.isState = this.$route.query.isState;
      if (id != null && id != "") {
        getCouponActivity(id).then((response) => {
          // console.log("查看", response.memberLevelList);
          this.stepThreeData.memberCondition = response.memberCondition;
          this.stepThreeData.memberLevelList = JSON.parse(
            response.memberLevelList
          );
          this.limitList = response.couponInfos
          this.stepThreeData.payMentList = JSON.parse(response.payMentList);
          this.stepThreeData.userMentList = JSON.parse(response.userMentList);
          if (!response.thresholdLadder) {
            response.thresholdLadder = [
              {
                value: "",
                couponList: [],
              },
            ];
          }
          this.createForm = response;
          if (this.isState === "3") {
            delete this.createForm.id;
          }
          // 获取 issueIds 列表
          const issueIds = this.createForm.issueIds;
          // 获取 couponList 并处理
          creationList({})
            .then((res) => {
              if (res.rows == null) {
                this.couponList = [];
              } else {
                this.couponList = res.rows;
                // 遍历 couponList，将符合条件的行填入 selectionCouponList
                this.selectionCouponList = this.couponList.filter((coupon) =>
                  issueIds.includes(coupon.id)
                );

              }
            })
            .finally(() => (this.couponLoading = false));
        });
      }
    },
    addThresholdLadder() {
      this.createForm.thresholdLadder.push({
        value: "",
        couponList: [],
      });
    },
    deleteThresholdLadder(rowIndex) {
      if (this.createForm.thresholdLadder.length <= 1) {
        return;
      }
      this.createForm.thresholdLadder.splice(rowIndex, 1);
      // this.createForm = { ...this.createForm };
    },
    updateAndSubmitForm() {
      this.createForm.memberCondition = this.stepThreeData.memberCondition;
      // this.createForm.memberLevel = JSON.stringify(
      //   this.stepThreeData.memberLevelList
      // );
      this.createForm.memberLevelList = JSON.stringify(
        this.stepThreeData.memberLevelList
      );
      this.createForm.userMentList = JSON.stringify(
        this.stepThreeData.userMentList
      );
      this.createForm.payMentList = JSON.stringify(
        this.stepThreeData.payMentList
      );
      if (!this.limitList.every((item) => {
        return this.checkVal(item)
      })) {
       return
      }
      // console.log("修改成功", this.createForm);
      this.$refs.createForm.validate((valid) => {
        if (valid) {
          // 拼接参数

          this.createForm.issueIds = this.selectionCouponList.map(
            (coupon) => coupon.id
          );
          const uniqueStationNames = [
            ...new Set(
              this.selectionCouponList.map((item) => item.stationName)
            ),
          ];
          const concatenatedStationNames = uniqueStationNames.join("/");
          this.createForm.stationName = concatenatedStationNames;
          this.createForm.userType = "all";

          // 设置修改模式为 true
          this.createForm.isEdit = true;

          if (this.createForm.distributionType === "0") {
            this.createForm.thresholdLadder = [
              {
                value: "0",
                couponList: [],
              },
            ];
          } else if (this.createForm.distributionType === "1") {
            this.createForm.activityThreshold = null;
          }

          this.submited = true;
          updateCouponActivity(this.createForm)
            .then((response) => {
              // console.log(response);
              this.msgSuccess("修改成功");
              this.$router.push({
                path: "/market/coupon/Coupon_CreateIssue",
                query: { activityId: response.data },
              });
            })
            .catch(() => {
              this.submited = false;
            });
        } else {
          // 如果表单校验失败，可以进行相应处理，比如提示用户填写正确的信息
          this.$message.error("请填写正确的信息");
        }
      });
    },
    setRepeatVal() {
      let newArr = this.createForm.thresholdLadder.map((m) => m.value);
      let arrSet = new Set(newArr);
      return arrSet.size == newArr.length;
    },
    submitForm() {
      this.createForm.memberCondition = this.stepThreeData.memberCondition;
      this.createForm.memberLevelList = JSON.stringify(
        this.stepThreeData.memberLevelList
      );
      this.createForm.userMentList = JSON.stringify(
        this.stepThreeData.userMentList
      );
      this.createForm.payMentList = JSON.stringify(
        this.stepThreeData.payMentList
      );
      // console.log(
      //   "添加成功",
      //   JSON.stringify(this.stepThreeData.memberLevelList)
      // );
      if (!this.setRepeatVal()) {
        return this.$message.error("门槛不能重复！！！");
      }
      this.$refs.createForm.validate((valid) => {
        if (valid) {
          if (this.selectionCouponList.length === 0) {
            this.$message.error("优惠券阈值不能为空");
            return;
          }
          // 拼接参数
          this.createForm.issueIds = this.selectionCouponList.map(
            (coupon) => coupon.id
          );
          // 获取 this.selectionCouponList 中所有不重复的 stationName
          const uniqueStationNames = [
            ...new Set(
              this.selectionCouponList.map((item) => item.stationName)
            ),
          ];
          this.createForm.couponInfos= this.limitList
          const concatenatedStationNames = uniqueStationNames.join("/");
          this.createForm.stationName = concatenatedStationNames;
          this.createForm.userType = "all";
          if (this.createForm.distributionType === "0") {
            this.createForm.thresholdLadder = [
              {
                value: "0",
                couponList: [],
              },
            ];
          } else if (this.createForm.distributionType === "1") {
            this.createForm.activityThreshold = null;
          }
          if (!this.limitList.every((item) => {
              return this.checkVal(item)
            })) {
            return
            }
          this.submited = true;
          addCouponActivity(this.createForm)
            .then((response) => {
              this.msgSuccess("添加成功");
              this.$router.push({
                path: "/market/coupon/Coupon_CreateIssue",
                query: { activityId: response.data },
              });
            })
            .catch(() => {
              this.submited = false;
            });
        } else {
          // 如果表单校验失败，可以进行相应处理，比如提示用户填写正确的信息
          this.$message.error("请填写正确的信息");
        }
      });
    },

    oneNextEvent() {
      if (this.selectOilList.length > 0) {
        this.$refs["ruleForm" + this.stepActive].validate((valid) => {
          if (valid) {
            this.stepActive++;
          } else {
            // console.log("error submit!!");
            return false;
          }
        });
      } else {
        this.$message.error("请选择油品！！！");
      }
    },
    delRowEvent(name, index, row) {
      // console.log(index);
      if (this.createForm.thresholdLadder.length > 0) {
        this.createForm.thresholdLadder.forEach((item) => {
          if (item.couponList.length > 0) {
            item.couponList = item.couponList.filter((f) => f != row.id);
          }
        });
      }
      this[name].splice(index, 1);
      if(this.selectionCouponList.length > 0) {
        this.getLimitList()
      }

    },
    backPreEvent() {
      this.stepActive--;
    },
    getStartTime() {
      this.createForm.activityStartTime = this.formatter(
        new Date(),
        "yyyy-MM-dd hh:mm:ss"
      );
    },
    addListEvent(n, i) {
      this[n][i].rules.push({ full: "", cut: "", cutMin: "", cutMax: "" });

      // console.log(this.selectOilList);
    },
    addRulesListEvent(n, i) {
      this.rules.push({ full: "", cut: "", cutMin: "", cutMax: "" });

      // console.log(this.selectOilList);
    },
    reduceListEvent(n, i) {
      // console.log(i);
      // console.log(n);
      n.splice(i, 1);
    },
    getOilListByLogin() {
      this.loading = true;
      getOilListByLogin()
        .then((res) => {
          this.oilList = res.rows;
          // console.log("this.oilList", this.oilList);
        })
        .finally(() => (this.loading = false));
    },
    getStationList() {
      this.stationOpen = true;
      this.loading = true;
      this.stationQuery = {
        enterpriseId: this.presentEnterprise.enterpriseId,
      };
      getStationList(this.stationQuery)
        .then((res) => {
          this.stationList = res.rows;
        })
        .finally(() => (this.loading = false));
    },

    getCouponList() {
      const curSelectCouponList = cloneDeep(this.selectionCouponList);
      this.couponOpen = true;
      this.couponLoading = true;
      const query = {
        status: 1,
      };

      creationList(query)
        .then((res) => {
          if (res.rows == null) {
            this.couponList = [];
          } else {
            this.couponList = res.rows;
          }
          this.$nextTick(() => {
            this.couponList.forEach((element) => {
              curSelectCouponList.forEach((row) => {
                if (element.id == row.id) {
                  this.$refs.couponTable.toggleRowSelection(element);
                }
              });
            });
          });
        })
        .finally(() => (this.couponLoading = false));

    },
    translateCodeToAddress(codeArr) {
      return translateAddress(codeArr);
    },
    handleSelectionOilChange(val) {
      this.selectOilList = val;
    },
    handleSelectionStationChange(val) {
      this.selectStationList = val;
    },
    handleSelectionCouponChange(val) {
      this.selectionCouponList = val;
      // this.$refs.createForm.validate((valid) => {});
    },
    formatter(thistime, fmt) {
      let $this = new Date(thistime);
      let o = {
        "M+": $this.getMonth() + 1,
        "d+": $this.getDate(),
        "h+": $this.getHours(),
        "m+": $this.getMinutes(),
        "s+": $this.getSeconds(),
        "q+": Math.floor(($this.getMonth() + 3) / 3),
        S: $this.getMilliseconds(),
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          ($this.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
        }
      }
      return fmt;
    },
  },
};
</script>
<style lang="scss" scoped>
.checkbox-b {
  width: 110px;
}
.checkbox-a {
  width: 52px;
}
.checkbox-super {
  width: 110px;
}
.redu_root {
  .alert-style {
    width: 50%;
    height: 40px;
    margin-left: 20px;
  }

  .disflx {
    display: flex;
  }

  .mt12 {
    margin-top: 12px;
  }

  .redu_title {
    height: 60px;
    font-size: 18px;
    line-height: 60px;
    font-weight: bold;
    background: #ccc;
    color: #000;
    text-indent: 30px;
  }

  .redu_step {
    width: 85%;
    margin: 24px auto;
  }

  .step_form {
    width: 85%;
    margin: 12px auto;

    .form-com-css {
      .el-form-item {
        // padding: 20px;
        padding-left: 0;
        // border: 1px solid #ccc;

        &.nolable {
          ::v-deep .el-form-item__content {
            margin-left: 20px !important;
          }
        }

        .t {
          &::before {
            content: "*";
            color: red;
            margin-right: 5px;
          }
        }

        .one-alert {
          align-items: center;
        }
      }
    }

    &.step_two {
      .form-com-css {
        .el-form-item {
          padding: 0 24px;

          &.nolable {
            padding: 20px 0;
          }

          .t {
            &::before {
              content: "*";
              color: red;
              margin-right: 5px;
            }
          }

          .tableStyle {
            margin: 20px 0;

            ::v-deep table {
              thead tr th,
              tbody tr td {
                padding: 0;
                text-align: center;
                background: transparent;
              }

              tbody tr td {
                padding: 5px 0;
              }
            }
          }

          .date-css {
            margin-bottom: 15px;

            .el-input {
              width: 50%;
            }
          }
        }
      }
    }

    &.step_three {
      .form-com-css {
        .three-one {
          padding: 20px 0;

          .t-top-tip {
            margin-left: 30px;
            margin-top: 12px;

            p {
              margin-bottom: 0;

              i {
                font-style: normal;
                margin-left: 24px;
                color: #1890ff;
              }
            }
          }
        }

        .three-list {
          .row-bg {
            margin: 12px 0;
          }

          margin: 20px 0;
        }

        .oilNameDiv {
          justify-content: space-between;
        }

        .three-b {
          margin: 12px 0;
          align-items: center;

          .el-alert {
            margin-left: 0;
          }

          .el-input {
            width: 60%;
          }
        }
      }
    }
  }
}

.border-c {
  margin-top: 22px;
  padding-bottom: 16px;
  border: 1px solid #ccc;
}
.using_limit {
  margin-top: 22px;
  padding: 16px 30px;
  border: 1px solid #ccc;
  .title {
    font-size: 14px;
    line-height: 40px;
  }
}
::v-deep .el-form-item__content {
  margin: 0 30px !important;
}
</style>
